﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace EuroAudit
{
    public partial class Search : System.Web.UI.Page
    {
        GlobalF GFunc = new GlobalF();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] == null | Session["UserName"].ToString() == "" | Session["UserName"].ToString() == "guest")
            {
                Response.Redirect("Login.aspx", true);
                //return;
            }
            GFunc.InitO();
            if (txtDocDate.Text.Length + txtDocName.Text.Length + txtDocNum.Text.Length + txtDocType.Text.Length > 0)
            {
                LoadDoc();
            }
            
            gvDocType.DataSource = GFunc.GetData("SELECT Nos, Info FROM spr WHERE RecStatus=0 AND SprID='DocType' GROUP BY Nos ORDER BY Nos", "WebCNS", false);
            //gvDocType.DataValueField = "Nos";
            //lbDocType.DataTextField = "Info";
            gvDocType.DataBind();

        }

        protected void cmdShowDocType_Click(object sender, EventArgs e)
        {
            gvDocType.Visible = !gvDocType.Visible;
        }

        protected void cmdShowDocDate_Click(object sender, EventArgs e)
        {
            cDocDate.Visible = !cDocDate.Visible;
        }

        protected void gvDocType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (txtDocType.Text.Length == 0)
            {
                txtDocType.Text = gvDocType.SelectedRow.Cells[1].Text;
            }
            else
            {
                txtDocType.Text = txtDocType.Text + "|" + gvDocType.SelectedRow.Cells[1].Text;
            }
        }

        protected void cDocDate_SelectionChanged(object sender, EventArgs e)
        {
            if (txtDocDate.Text.Length == 0)
            {
                txtDocDate.Text = cDocDate.SelectedDate.ToString("dd.MM.yyyy");
            }
            else
            {
                txtDocDate.Text = txtDocDate.Text + ".." + cDocDate.SelectedDate.ToString("dd.MM.yyyy");
            }
        }

        void LoadDoc()
        {
            string[] spDocType = null;//dokumentu tipu masīvs
            string WhereDocType = "";//dokumenta tipa parametrs
            string WhereDocNum = "";//dokumenta numura parametrs
            string[] spPeriod = null;//datumu masīvs no txtDocDate
            string WhereDocDate = "";//dokumenta datuma parametrs
            string WhereDocName = "";//dokumenta nosaukuma parametrs
            string WhereAccOrg = " AND (org.AccessU LIKE '%;guest;%' " + Session["WhereGroups"].ToString().Replace("AccessU", "org.AccessU").Replace("AccessG", "org.AccessG") + ")";//pieejas tiesības organizācijām
            string WhereAccDocType = " AND (spr.AccessU LIKE '%;guest;%' " + Session["WhereGroups"].ToString().Replace("AccessU", "spr.AccessU").Replace("AccessG", "spr.AccessG") + ")";//pieejas tiesības dokumentu tipiem
            Button cmdEdit;
            Button cmdShowDoc;
            TableRow trNewRow;
            TableCell tcNewCell;
            TableRow thrNewRow;
            TableCell thcNewCell;

            try
            {
                lblErr.Text = "";
                if (txtDocType.Text.Length > 0)
                {
                    spDocType = txtDocType.Text.Split('|');
                    WhereDocType = " AND (doc.DocType='" + spDocType[0].Trim() + "'";
                    for (int i = 1; i < spDocType.GetLength(0); i++)
                    {
                        WhereDocType = WhereDocType + " OR doc.DocType='" + spDocType[i].Trim() + "'";
                    }
                    WhereDocType = WhereDocType + ") ";
                }
                if (txtDocDate.Text.Length > 0)
                {
                    DateTime DocD;
                    spPeriod = txtDocDate.Text.Split(new string[] { ".." }, StringSplitOptions.RemoveEmptyEntries);
                    if (spPeriod.GetLength(0) == 1)
                    {
                        DocD = DateTime.ParseExact(spPeriod[0], "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                        WhereDocDate = " AND (doc.DocDate='" + DocD.ToString("yyyy-MM-dd") + "') ";
                    }
                    else
                    {
                        DocD = DateTime.ParseExact(spPeriod[0], "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                        WhereDocDate = " AND (doc.DocDate BETWEEN '" + DocD.ToString("yyyy-MM-dd") + "' AND ";
                        DocD = DateTime.ParseExact(spPeriod[1], "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
                        WhereDocDate = WhereDocDate + "'" + DocD.ToString("yyyy-MM-dd") + "') ";
                    }
                }
                if (txtDocNum.Text.Length > 0)
                {
                    spDocType = txtDocNum.Text.Split('|');
                    WhereDocNum = " AND (doc.DocNum='" + spDocType[0].Trim() + "'";
                    for (int i = 1; i < spDocType.GetLength(0); i++)
                    {
                        WhereDocNum = WhereDocNum + " OR doc.DocNum='" + spDocType[i].Trim() + "'";
                    }
                    WhereDocNum = WhereDocNum + ") ";
                }
                if (txtDocName.Text.Length > 0)
                {
                    spDocType = txtDocName.Text.Split('|');
                    WhereDocName = " AND (doc.DocName='" + spDocType[0].Trim() + "'";
                    for (int i = 1; i < spDocType.GetLength(0); i++)
                    {
                        WhereDocName = WhereDocName + " OR doc.DocName='" + spDocType[i].Trim() + "'";
                    }
                    WhereDocName = WhereDocName + ") ";
                }

                string QStr = "SELECT doc.DocID, doc.OrgID, org.OrgName, doc.DocType, doc.DocDate, doc.DocNum, doc.DocName, doc.DocDescr, doc.Link " +
                        "FROM (doc LEFT JOIN org ON doc.OrgID = org.OrgID) LEFT JOIN spr ON doc.DocType = spr.Nos " +
                        "WHERE doc.RecStatus=0 AND spr.SprID='DocType' " + WhereDocType + WhereDocNum + WhereDocDate + WhereDocName + WhereAccOrg + WhereAccDocType + " " +
                        "ORDER BY org.OrgName, doc.DocType, doc.DocDate";
                DataSet dsResult = GFunc.GetData(QStr, "WebCNS", false);

                tResults.Rows.Clear();
                if (dsResult.Tables.Count > 0)
                {
                    if (dsResult.Tables[0].Rows.Count > 0)
                    {
                        thrNewRow = new TableHeaderRow();
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = "Labot";
                        thrNewRow.Cells.Add(thcNewCell);
                        thcNewCell = new TableHeaderCell();
                        thcNewCell.Text = "Ielādēt";
                        thrNewRow.Cells.Add(thcNewCell);
                        foreach (DataColumn Col in dsResult.Tables[0].Columns)
                        {
                            thcNewCell = new TableHeaderCell();
                            thcNewCell.Text = Col.ColumnName;
                            thrNewRow.Cells.Add(thcNewCell);
                        }
                        tResults.Rows.AddAt(0, thrNewRow);

                        foreach (DataRow row in dsResult.Tables[0].Rows)
                        {
                            trNewRow = new TableRow();
                            //pievienojam rediģēšanas komandu
                            tcNewCell = new TableCell();
                            //if (Session["IsAdmin"].ToString() == "1")
                            //{
                            cmdEdit = new Button();
                            cmdEdit.ID = "DocEdit" + row["DocID"].ToString();
                            cmdEdit.Text = "Labot";
                            cmdEdit.CssClass = "cmdEdit";
                            cmdEdit.Click += new EventHandler(cmdEdit_Click);
                            tcNewCell.Controls.Add(cmdEdit);
                            //}
                            trNewRow.Cells.Add(tcNewCell);
                            //pievienojam dok. ielādes komandu
                            tcNewCell = new TableCell();
                            //if (Session["IsAdmin"].ToString() == "1")
                            //{
                            cmdShowDoc = new Button();
                            cmdShowDoc.ID = "ShowDoc" + row["DocID"].ToString();
                            cmdShowDoc.Text = "Ielādēt";
                            cmdShowDoc.CssClass = "cmdEdit";
                            //cmdShowDoc.PostBackUrl = GlobalF.AppOptions["DocPath"] + row["Link"].ToString();
                            cmdShowDoc.Click += new EventHandler(cmdShowDoc_Click);
                            tcNewCell.Controls.Add(cmdShowDoc);
                            //}
                            trNewRow.Cells.Add(tcNewCell);

                            foreach (DataColumn Col in dsResult.Tables[0].Columns)
                            {
                                tcNewCell = new TableCell();
                                string a = Col.DataType.Name;
                                if (Col.DataType.Name == "DateTime")
                                {
                                    DateTime DT = (DateTime)row[Col];
                                    tcNewCell.Text = DT.ToString("dd.MM.yyyy");
                                }
                                else
                                {
                                    tcNewCell.Text = row[Col].ToString() + "";
                                }
                                trNewRow.Cells.Add(tcNewCell);
                            }
                            tResults.Rows.Add(trNewRow);

                        }
                    }
                }
            }
            catch(Exception ex)
            {
                lblErr.Text = ex.Message;
            }
        }

        void cmdShowDoc_Click(object sender, EventArgs e)
        {
            string DocID;
            string QString;
            DataSet ds;

            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            DocID = b.ID.Substring(7);
            QString = "SELECT * FROM doc WHERE RecStatus=0 AND DocID='" + DocID + "'";
            ds = GFunc.GetData(QString, "WebCNS", false);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    Response.Redirect(GlobalF.AppOptions["DocPath"] + row["Link"].ToString(), true);
                }
            }
        }

        void cmdEdit_Click(object sender, EventArgs e)
        {
            string DocID;
            System.Web.UI.WebControls.Button b = sender as System.Web.UI.WebControls.Button;
            DocID = b.ID.Substring(7);
            Response.Redirect("doclist.aspx?DocEdit=" + DocID, true);
            //throw new NotImplementedException();
        }

        protected void cmdFind_Click(object sender, EventArgs e)
        {
            if (txtDocDate.Text.Length + txtDocName.Text.Length + txtDocNum.Text.Length + txtDocType.Text.Length > 0)
            {
                lblErr.Text = "";
                LoadDoc();
                upResults.Update();
            }
            else
            {
                lblErr.Text = "Nav norādīts neviens parametrs.";
            }
        }
    }
}
